package com.rdzn.mall.portal.config.shiro;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.rdzn.mall.portal.config.authc.vo.DefContants;
import com.rdzn.mall.portal.domain.MemberDetails;
import com.rdzn.mall.portal.service.IUserService;
import com.rdzn.mall.portal.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 鉴权登录拦截器
 * @Author: Scott
 * @Date: 2018/10/7
 **/
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE)
public class JwtTokenFilter implements Filter {

	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private IUserService userService;

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
		String token = httpServletRequest.getHeader(DefContants.X_ACCESS_TOKEN);
		if (StringUtils.isBlank(token)) {
			log.info("filter token is null");
//			throw new AuthenticationException("token is null");
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
		String username = jwtTokenUtil.getUserNameFromToken(token);
		if (username == null) {
			log.info("token非法无效!");
			filterChain.doFilter(servletRequest, servletResponse);
		}
		MemberDetails userDetails = userService.getUserDetails(username);
		if (userDetails.getUmsMember() == null) {
			log.info("用户不存在!");
			filterChain.doFilter(servletRequest, servletResponse);
		}
		UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
		log.debug("authenticated user:{}", username);
		SecurityContextHolder.getContext().setAuthentication(authentication);
		filterChain.doFilter(servletRequest, servletResponse);
	}
}
